<?php
/**
 * Name: 初始化服务.
 * User: 董坤鸿
 * Date: 2016/10/13
 * Time: 10:46
 */

namespace App\Services;

use App\Models\AcceptRecord;
use App\Models\Customer;
use App\Models\Project;
use App\Models\WxClient;

class IndexService
{

    /**
     * 初始化数据
     */
    public function init()
    {
        $user = request()->user();  //获取当前登录用户信息
        $projects = Project::where('users', $user->id)->get(['title', 'wx_id', 'plugins', 'users']);  //获取当前用户所属项目
        if (!empty($projects)) {
            foreach ($projects as $v) {
                if (count($v['users']) === 1 && $v['users'][0] === $user->id) {
                    $v['needAutoAccept'] = true;
                } else {
                    $v['needAutoAccept'] = false;
                }
                unset($v['users']);
            }
        }
        $project_wx = $projects->pluck('wx_id', 'id')->all();
        $wxClients = [];
        //获取到各个微信可见用户
        foreach ($project_wx as $project_id => $wx_id) {
            foreach ($wx_id as $id) {
                array_push($wxClients, $this->isAccepted($id, $user));
            }
        }
        return compact('user', 'projects', 'wxClients');
    }

    /**
     * 验证是否被认领
     * @param $wx_id
     * @return null
     */
    public function isAccepted($wx_id, $user)
    {
        $client = WxClient::find($wx_id);
        if (is_null($client)) return null;
        $wx_client = $client->toArray();

        if (isset($wx_client['contacts'])) {
            $contacts = [];
            foreach ($wx_client['contacts'] as $key => $customer) {
                $acceptRecord = AcceptRecord::where(['customers' => $customer['customer_id'], 'project_id' => $wx_client['project_id']])->first();
                /**@var Customer $result * */
                $result = Customer::find($customer['customer_id']);
                $customer['name'] = $result->getAttribute('baseInfo.name');
                if (is_null($acceptRecord)) {
                    $customer['isAccepted'] = 0;
                } else {
                    if ($acceptRecord->user_id === $user->id) {
                        $customer['isAccepted'] = 1;
                    } else {
                        if ($user->isManager) {
                            $customer['isAccepted'] = -1;
                        } else {
                            $customer = null;
                        }
                    }
                }
                if (!is_null($customer)) array_push($contacts, $customer);
            }
            $wx_client['contacts'] = $contacts;
        } else {
            $wx_client['contacts'] = [];
        }
        return $wx_client;
    }
}